"""批量创建用户与文章的脚本。

用法：
  python -m tests.scripts.bulk_create --users 10 --articles 20
选项：
  --as-admin 为第一个创建的用户赋予管理员权限
"""

import os
import argparse
from faker import Faker

from app import create_app, db
from app.models import User, Article, ArticleVisibility


def main():
	parser = argparse.ArgumentParser()
	parser.add_argument("--users", type=int, default=5)
	parser.add_argument("--articles", type=int, default=10)
	parser.add_argument("--as-admin", action="store_true")
	args = parser.parse_args()

	os.environ.setdefault("DB_TYPE", "sqlite")
	os.environ.setdefault("SQLITE_PATH", os.path.join(os.getcwd(), "rbac.sqlite3"))

	app = create_app(os.getenv("FLASK_ENV", "development"))
	fake = Faker()

	with app.app_context():
		db.create_all()
		users = []
		for i in range(args.users):
			u = User(username=fake.user_name() + str(fake.random_int()), email=fake.unique.email())
			u.set_password("Pass@123")
			db.session.add(u)
			users.append(u)

		# 确保用户获得主键 id（即使不设置管理员也要 flush）
		db.session.flush()

		if args.as_admin and users:
			users[0].is_admin = True
			db.session.add(users[0])
			db.session.flush()

		for _ in range(args.articles):
			author = fake.random_element(users)
			art = Article(
				title=fake.sentence(nb_words=6),
				content=fake.paragraph(nb_sentences=5),
				visibility=fake.random_element([ArticleVisibility.public, ArticleVisibility.private]),
				author_id=author.id
			)
			db.session.add(art)

		db.session.commit()
		print(f"Created {len(users)} users and {args.articles} articles.")


if __name__ == "__main__":
	main()


